<?php


namespace Yond\LaravelDomain\Models\Concerns;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Kalnoy\Nestedset\NodeTrait;

/**
 * Trait NestedSet
 * @mixin Model
 */
trait NestedSet
{
    use NodeTrait;

    // public function initializeNestedSet()
    // {
    //     $this->append('parents')->makeHidden(['ancestors', 'descendants', '_lft', '_rgt'])->mergeFillable(['parents']);
    // }

    public function getParentsAttribute()
    {
        return $this->loadMissing('ancestors')
            ->ancestors
            ->whenEmpty(function ($collection) {
                return $collection->push(['id' => 0]);
            })
            ->pluck('id');
    }

    /**
     * @throws \Exception
     */
    public function setParentsAttribute(array $value)
    {
        try {
            $this->setParentIdAttribute($value[array_key_last($value)]);
        } catch (\LogicException $e) {
            throw ValidationException::withMessages(['parents' => trans($e->getMessage())]);
        }
    }
}